const { getApiUrl } = require('../../config/config.js')

// 获取应用实例
const app = getApp()

Page({
  data: {
    title: '',
    content: '',
    images: [], // 存储图片数据，包含路径和上传状态
    isAnonymous: false,
    isSubmitting: false,
    maxContentLength: 800,
    maxImageCount: 9,
    canPublish: false,
    selectedType: null, // 存储类型ID (数字1-6)
    selectedTypeName: '', // 存储类型名称，用于显示
    showDraftModal: false,
    showTypeModal: false,
    isBeautifying: false, // 是否正在美化
    contentAnimating: false, // 内容美化动画状态
    
    // 帖子类型数据
    types: [
      {
        id: 1,
        name: '校园公告',
        icon: '/images/icons/study.png'
      },
      {
        id: 2,
        name: '学术学习',
        icon: '/images/icons/life.png'
      },
      {
        id: 3,
        name: '校园生活',
        icon: '/images/icons/emotion.png'
      },
      {
        id: 4,
        name: '社交兴趣',
        icon: '/images/icons/activity.png'
      },
      {
        id: 5,
        name: '就业实习',
        icon: '/images/icons/search.png'
      },
      {
        id: 6,
        name: '校园服务',
        icon: '/images/icons/other.png'
      }
    ],
    
    // 标签相关数据
    selectedTags: [], // 已选标签
    recommendedTags: ['活动', '社团', '学习', '日常', '二手', '问答', '通知', '树洞', '音乐节', '校园活动', '乐队'], 
    showingCustomTagInput: false,
    customTag: '',
    maxTagCount: 5,
    maxTagLength: 10
  },

  onLoad() {
    // 检查是否有草稿
    const draft = wx.getStorageSync('postDraft')
    if (draft) {
      this.setData({
        showDraftModal: true
      })
    } else {
      this.checkLoginStatus();
    }
  },
    
  // 检查登录状态
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      wx.showModal({
        title: '提示',
        content: '发帖需要先登录，是否前往登录？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            })
          } else {
            wx.switchTab({ url: '/pages/index/index' })
          }
        }
      })
      return false;
    }
    return true;
  },

  // 加载草稿
  loadDraft() {
    const draft = wx.getStorageSync('postDraft')
    if (draft) {
      this.setData({
        title: draft.title || '',
        content: draft.content || '',
        images: draft.images || [],
        isAnonymous: draft.isAnonymous || false,
        selectedType: draft.selectedType || null,
        selectedTypeName: draft.selectedTypeName || '',
        selectedTags: draft.selectedTags || [],
        showDraftModal: false
      }, () => {
        this.checkCanPublish()
      })
    }
  },

  // 清除草稿
  clearDraft() {
    wx.removeStorageSync('postDraft')
    this.setData({
      title: '',
      content: '',
      images: [],
      isAnonymous: false,
      selectedType: null,
      selectedTypeName: '',
      selectedTags: [],
      showDraftModal: false
    })
  },

  // 保存草稿
  saveDraft() {
    const {title, content, images, isAnonymous, selectedType, selectedTypeName, selectedTags} = this.data
    
    if (title.trim() || content.trim() || images.length > 0 || selectedTags.length > 0) {
      const draft = {
        title,
        content,
        images,
        isAnonymous,
        selectedType,
        selectedTypeName,
        selectedTags,
        saveTime: new Date().toLocaleString()
      }
      
      wx.setStorageSync('postDraft', draft)
      
      wx.showToast({
        title: '草稿已保存',
        icon: 'success',
        duration: 1000
      })
    }
  },

  // 检查是否可以发布
  checkCanPublish() {
    const hasContent = !!(this.data.content.trim() || this.data.title.trim());
    const hasType = !!this.data.selectedType;
    const canPublish = hasContent && hasType;
    
    if (this.data.canPublish !== canPublish) {
      this.setData({ canPublish });
    }
  },

  // 取消发布，返回首页
  discardDraft() {
    if (this.data.title.trim() || this.data.content.trim() || this.data.images.length > 0) {
      wx.showModal({
        title: '提示',
        content: '是否保存为草稿？',
        confirmText: '保存草稿',
        confirmColor: '#07c160',
        cancelText: '不保存',
        cancelColor: '#999999',
        success: (res) => {
          if (res.confirm) {
            this.saveDraft();
          } else {
            this.clearDraft();
          }
          wx.switchTab({ url: '/pages/index/index' });
        }
      });
    } else {
      wx.switchTab({ url: '/pages/index/index' });
    }
  },

  // 处理标题输入
  handleTitleInput(e) {
    this.setData({
      title: e.detail.value
    }, () => {
      this.checkCanPublish()
    })
  },

  // 处理内容输入
  handleContentInput(e) {
    // 限制最大字数
    let content = e.detail.value;
    if (content.length > this.data.maxContentLength) {
      content = content.slice(0, this.data.maxContentLength);
    }
    
    this.setData({
      content: content
    }, () => {
      this.checkCanPublish()
    })
  },

  // 美化内容
  beautifyContent() {
    // 检查是否有内容可美化
    if (!this.data.content.trim()) {
      wx.showToast({
        title: '请先输入内容',
        icon: 'none'
      });
      return;
    }

    // 设置正在美化状态
    this.setData({
      isBeautifying: true
    });

    // 准备请求数据
    const requestData = {
      content: this.data.content.trim()
    };

    // 发送请求到服务器
    wx.request({
      url: getApiUrl('/upload/beautify'),
      method: 'POST',
      data: requestData,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        // 检查请求是否成功
        if (res.data && res.data.code === 200 && res.data.data) {
          const { beautifiedContent, isBeautified } = res.data.data;
          
          // 如果美化成功且内容有变化
          if (isBeautified && beautifiedContent) {
            // 延迟一下，让动画效果更明显
            setTimeout(() => {
              this.setData({
                content: beautifiedContent,
                isBeautifying: false,
                contentAnimating: true // 添加动画状态
              });
              
              // 通过定时器控制动画结束后取消动画状态
              setTimeout(() => {
                this.setData({
                  contentAnimating: false
                });
              }, 1500);
              
              wx.showToast({
                title: '内容已美化',
                icon: 'success'
              });
            }, 1200);
          } else {
            // 内容没有变化
            this.setData({ isBeautifying: false });
            wx.showToast({
              title: '内容已经很完美了',
              icon: 'none'
            });
          }
        } else {
          // 请求返回错误
          this.setData({ isBeautifying: false });
          wx.showToast({
            title: (res.data && res.data.message) || '美化失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: () => {
        // 请求失败
        this.setData({ isBeautifying: false });
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 切换匿名状态
  toggleAnonymous() {
    this.setData({
      isAnonymous: !this.data.isAnonymous
    })
  },

  // 选择图片
  chooseImage() {
    const that = this;
    const currentCount = this.data.images.length;
    
    if (currentCount >= this.data.maxImageCount) {
      wx.showToast({
        title: `最多选择${this.data.maxImageCount}张图片`,
        icon: 'none'
      });
      return;
    }

    wx.chooseImage({
      count: this.data.maxImageCount - currentCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        // 添加新图片到列表，状态为待上传
        const newImages = res.tempFilePaths.map(path => ({
          path,
          status: 'waiting' // waiting, uploading, done, fail
        }));
        
        that.setData({
          images: [...that.data.images, ...newImages]
        });
        
        // 上传新添加的图片
        that.uploadImages(newImages);
      }
    });
  },

  // 上传图片
  uploadImages(newImages) {
    const that = this;
    const images = [...this.data.images];
    
    newImages.forEach((image, idx) => {
      const imageIndex = images.findIndex(img => img.path === image.path);
      if (imageIndex === -1) return;
      
      // 更新状态为上传中
      images[imageIndex].status = 'uploading';
      that.setData({ images });
      
      // 上传图片到服务器
      wx.uploadFile({
        url: getApiUrl('/upload/avatar'),
        filePath: image.path,
        name: 'file',
        formData: {
          'user': 'test'
        },
        success: function(res) {
          try {
            const data = JSON.parse(res.data);
            if (data.code === 200) {
              // 更新上传成功的图片信息
              images[imageIndex].status = 'done';
              images[imageIndex].url = data.data; // 保存服务器返回的URL
              that.setData({ images });
            } else {
              // 上传失败
              images[imageIndex].status = 'fail';
              that.setData({ images });
              wx.showToast({
                title: data.message || '图片上传失败',
                icon: 'none'
              });
            }
          } catch (e) {
            // 处理JSON解析错误
            images[imageIndex].status = 'fail';
            that.setData({ images });
            wx.showToast({
              title: '图片上传失败',
              icon: 'none'
            });
          }
        },
        fail: function() {
          // 上传失败
          images[imageIndex].status = 'fail';
          that.setData({ images });
          wx.showToast({
            title: '图片上传失败',
            icon: 'none'
          });
        }
      });
    });
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.images];
    images.splice(index, 1);
    this.setData({
      images
    });
  },

  // 预览图片
  previewImage(e) {
    const current = e.currentTarget.dataset.url;
    const urls = this.data.images.map(img => img.status === 'done' ? img.url : img.path);
    
    wx.previewImage({
      current,
      urls
    });
  },

  // 显示类型选择弹窗
  showTypeModal() {
    this.setData({
      showTypeModal: true
    });
  },

  // 隐藏类型选择弹窗
  hideTypeModal() {
    this.setData({
      showTypeModal: false
    });
  },

  // 选择类型
  selectType(e) {
    const typeId = e.currentTarget.dataset.type;
    const selectedType = this.data.types.find(item => item.id === Number(typeId));
    
    if (selectedType) {
      this.setData({
        selectedType: selectedType.id,
        selectedTypeName: selectedType.name,
        showTypeModal: false
      }, () => {
        this.checkCanPublish();
      });
    }
  },
  
  // 阻止冒泡
  stopPropagation() {
    return;
  },
  
  // 确认类型选择
  confirmType() {
    this.hideTypeModal();
    this.checkCanPublish();
  },

  // 选择标签
  selectTag(e) {
    const tag = e.currentTarget.dataset.tag;
    // 检查是否已达到最大标签数
    if (this.data.selectedTags.length >= this.data.maxTagCount) {
          wx.showToast({
        title: `最多选择${this.data.maxTagCount}个标签`,
            icon: 'none'
      });
      return;
        }
    // 检查标签是否已存在
    if (this.data.selectedTags.includes(tag)) {
        wx.showToast({
        title: '已添加该标签',
          icon: 'none'
      });
      return;
    }
    // 添加标签
    this.setData({
      selectedTags: [...this.data.selectedTags, tag]
    });
  },

  // 移除标签
  removeTag(e) {
    const index = e.currentTarget.dataset.index;
    const newTags = [...this.data.selectedTags];
    newTags.splice(index, 1);
    this.setData({
      selectedTags: newTags
    });
  },

  // 显示自定义标签输入框
  showCustomTagInput() {
    // 检查是否已达到最大标签数
    if (this.data.selectedTags.length >= this.data.maxTagCount) {
      wx.showToast({
        title: `最多选择${this.data.maxTagCount}个标签`,
        icon: 'none'
      });
      return;
    }
    this.setData({
      showingCustomTagInput: true,
      customTag: ''
    });
  },

  // 处理自定义标签输入
  handleCustomTagInput(e) {
    this.setData({
      customTag: e.detail.value
    });
  },

  // 添加自定义标签
  addCustomTag() {
    const tag = this.data.customTag.trim();
    
    // 检查标签是否为空
    if (!tag) {
      wx.showToast({
        title: '标签不能为空',
        icon: 'none'
      });
      return;
    }
    
    // 检查标签长度
    if (tag.length > this.data.maxTagLength) {
      wx.showToast({
        title: `标签最多${this.data.maxTagLength}个字符`,
        icon: 'none'
      });
      return;
    }

    // 检查是否已达到最大标签数
    if (this.data.selectedTags.length >= this.data.maxTagCount) {
      wx.showToast({
        title: `最多选择${this.data.maxTagCount}个标签`,
        icon: 'none'
      });
      return;
    }

    // 检查标签是否已存在
    if (this.data.selectedTags.includes(tag)) {
      wx.showToast({
        title: '已添加该标签',
        icon: 'none'
      });
      return;
    }
    
    // 添加标签
    this.setData({
      selectedTags: [...this.data.selectedTags, tag],
      showingCustomTagInput: false,
      customTag: ''
    });
  },

  // 取消添加自定义标签
  cancelCustomTag() {
    this.setData({
      showingCustomTagInput: false,
      customTag: ''
    });
  },

  // 发布帖子
  publishPost() {
    // 检查登录状态
    if (!this.checkLoginStatus()) return;

    // 获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo.id) {
      wx.showToast({ 
        title: '用户信息异常，请重新登录', 
        icon: 'none' 
      });
      return;
    }

    // 验证内容
    if (!this.data.content.trim() && !this.data.title.trim()) {
      wx.showToast({ 
        title: '请输入内容或标题', 
        icon: 'none' 
      });
      return;
    }

    if (!this.data.selectedType) {
      wx.showToast({ 
        title: '请选择帖子类型', 
        icon: 'none' 
      });
      return;
    }
    
    // 检查图片是否都上传完成
    const hasUploadingImages = this.data.images.some(img => img.status === 'uploading');
    if (hasUploadingImages) {
      wx.showToast({
        title: '图片上传中，请稍候',
        icon: 'none'
      });
      return;
    }
    
    // 设置提交状态
    this.setData({
      isSubmitting: true
    });

    // 准备上传图片URLs
    const imageUrls = this.data.images
      .filter(img => img.status === 'done')
      .map(img => img.url || '');
    
    // 构造图片字段
    const imageFields = {};
    for (let i = 0; i < 9; i++) {
      const fieldName = `image${i+1}`;
      imageFields[fieldName] = i < imageUrls.length ? imageUrls[i] : null;
    }

    // 准备发布数据
      const postData = {
        authorId: userInfo.id, // 添加作者ID
        title: this.data.title.trim(),
        content: this.data.content.trim(),
      type: this.data.selectedType, // 发送数字ID
      tags: this.data.selectedTags,
      isAnonymous: this.data.isAnonymous ? 1 : 0,
      ...imageFields // 展开图片字段
    };

    wx.showLoading({
      title: '发布中...',
    });

    // 发送请求到服务器
        wx.request({
          url: getApiUrl('/post/create'),
          method: 'POST',
          data: postData,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        this.setData({
          isSubmitting: false
        });
        
        if (res.data && res.data.code === 200) {
        wx.showToast({
          title: '发布成功',
            icon: 'success'
          });

        // 清除草稿
          this.clearDraft();
          
          // 延迟返回上一页
        setTimeout(() => {
          wx.switchTab({
              url: '/pages/index/index'
            });
          }, 1500);
      } else {
          wx.showToast({
            title: (res.data && res.data.message) || '发布失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        this.setData({
          isSubmitting: false
        });
      wx.showToast({
          title: '网络错误，请重试',
        icon: 'none'
        });
      }
    });
  },
  
  // 确认使用草稿
  continueDraft() {
    this.loadDraft();
  },
  
  // 不使用草稿，丢弃
  discardDraftAndContinue() {
    this.clearDraft();
    this.setData({
      showDraftModal: false
    });
  }
}) 